package cn.zwz.data.controller;


import cn.zwz.basics.baseVo.Result;
import cn.zwz.basics.utils.ResultUtil;
import cn.zwz.data.entity.OrdersEntity;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Slf4j // 日志
@Api(tags = "订单接口") // 接口文档
@RestController
@RequestMapping("/zwz/orders")
@Transactional // 开启事务
public class OrdersController {

    //创建数据库连接池
    String url = "jdbc:mysql://localhost:3306/s001?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai";
    String username = "root";
    String password = "";
    DataSource dataSource = new DriverManagerDataSource(url, username, password);
    //创建JDBCTemplate
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

    /**
     * 后端列表
     */
    @ApiOperation(value = "订单列表")
    @RequestMapping("/page")
    public Result<List<OrdersEntity>> page(@RequestParam String page, @RequestParam String limit, @RequestParam String status, @RequestParam(required = false) String orderid) {
        int pageNum = Integer.parseInt(page); // 当前页
        int pageSize = Integer.parseInt(limit); // 每页条数
        int offset = (pageNum - 1) * pageSize; // 偏移量
        String sql;
        Object[] params;
        if (orderid == null || orderid.isEmpty()) {
            sql = "SELECT * FROM a_orders WHERE `status` = ? ORDER BY id DESC LIMIT ?, ?";
            params = new Object[]{status, offset, pageSize};
        } else {
            sql = "SELECT * FROM a_orders WHERE `status` = ? AND orderid = ? ORDER BY id DESC LIMIT ?, ?";
            params = new Object[]{status, orderid, offset, pageSize};
        }
        List<OrdersEntity> ordersList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(OrdersEntity.class), params);
        return new ResultUtil<List<OrdersEntity>>().setData(ordersList);
    }

    @ApiOperation(value = "对应用户订单列表")
    @RequestMapping("/userOrderPage")
    public Result<List<OrdersEntity>> userOrderPage(@RequestParam String page, @RequestParam String limit, @RequestParam String status, @RequestParam String userid) {
        int pageNum = Integer.parseInt(page); // 当前页
        int pageSize = Integer.parseInt(limit); // 每页条数
        int offset = (pageNum - 1) * pageSize; // 偏移量

        System.err.println(offset);
        System.err.println(pageSize);
        String sql;
        Object[] params;

        sql = "SELECT * FROM a_orders WHERE `status` = ? AND userid = ? ORDER BY id DESC LIMIT ?, ?";
        params = new Object[]{status, userid, offset, pageSize};
        List<OrdersEntity> ordersList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(OrdersEntity.class), params);
        return new ResultUtil<List<OrdersEntity>>().setData(ordersList);
    }

    /**
     * 前端列表
     */
    @RequestMapping("/list")
    public Result list(@RequestParam Map<String, Object> params, OrdersEntity orders, HttpServletRequest request) {
        return null;
    }

    /**
     * 列表
     */
    @RequestMapping("/lists")
    public Result list(OrdersEntity orders) {
        return null;
    }

    /**
     * 查询
     */
    @RequestMapping("/query")
    public Result query(OrdersEntity orders) {
        return null;
    }

    /**
     * 后端详情
     */
    @RequestMapping("/info/{id}")
    public Result info(@PathVariable("id") Long id) {
        return null;
    }

    /**
     * 前端详情
     */
    @RequestMapping("/detail/{id}")
    public Result detail(@PathVariable("id") Long id) {
        return null;
    }


    /**
     * 后端保存
     */
    @RequestMapping("/save")
    public Result save(@RequestBody OrdersEntity orders, HttpServletRequest request) {
        return null;
    }

    /**
     * 创建订单
     */
    /**
     * 创建订单
     */
    @PostMapping("/add")
    public Result add(@RequestBody OrdersEntity order) throws JsonProcessingException {
        if (order.getOrderid() == null || order.getOrderid().isEmpty()) {
            return new ResultUtil<>().setErrorMsg("订单号不能为空");
        }

        String checkSql = "SELECT COUNT(*) FROM a_orders WHERE orderid = ?";
        int count = jdbcTemplate.queryForObject(checkSql, new Object[]{order.getOrderid()}, Integer.class);
        if (count > 0) {
            return new ResultUtil<>().setErrorMsg("订单已存在");
        }

        order.setId(new Date().getTime() + Double.valueOf(Math.floor(Math.random() * 1000)).longValue());
        order.setAddtime(new Date());

        ObjectMapper objectMapper = new ObjectMapper();
        String itemsJson = objectMapper.writeValueAsString(order.getItems()); // 将items转换为JSON字符串

        String sql = "INSERT INTO a_orders " +
                "(id, addtime, orderid, tablename, userid, total, discounttotal, type, status, address, items_json) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        int update = jdbcTemplate.update(
                sql,
                order.getId(),
                order.getAddtime(),
                order.getOrderid(),
                order.getTablename(),
                order.getUserid(),
                order.getTotal(),
                order.getDiscounttotal(),
                order.getType(),
                order.getStatus(),
                order.getAddress(),
                itemsJson);

        if (update != 1) {
            return new ResultUtil<>().setErrorMsg("生成订单失败");
        }

        return new ResultUtil<>().setData(null);
    }

    /**
     * 核销订单
     */
    @ApiOperation(value = "用户支付订单")
    @GetMapping("/repayOrder")
    public Result repayOrder(@RequestParam String orderid) {
        if (orderid == null || orderid.isEmpty()) {
            return new ResultUtil<>().setErrorMsg("订单号不能为空");
        }
        String sql = "UPDATE a_orders SET `status` = '已支付'  WHERE orderid = ?";
        int update = jdbcTemplate.update(sql, orderid);
        if (update == 1) {
            return new ResultUtil<>().setData(null);
        } else {
            return new ResultUtil<>().setErrorMsg("支付失败");
        }
    }
    /**
     * 核销订单
     */
    @ApiOperation(value = "核销订单")
    @GetMapping("/update")
    public Result update(@RequestParam String orderid) {
        if (orderid == null || orderid.isEmpty()) {
            return new ResultUtil<>().setErrorMsg("订单号不能为空");
        }
        String sql = "UPDATE a_orders SET `status` = '已完成'  WHERE orderid = ?";
        int update = jdbcTemplate.update(sql, orderid); // 执行sql语句
        if (update == 1) {
            return new ResultUtil<>().setData(null);
        } else {
            return new ResultUtil<>().setErrorMsg("修改失败");
        }
    }

    //    取消订单
    @ApiOperation(value = "取消订单")
    @GetMapping("/cancel")
    public Result cancel(@RequestParam String orderid) {
        System.err.println("orderid:" + orderid);
        if (orderid == null || orderid.isEmpty()) {
            return new ResultUtil<>().setErrorMsg("订单号不能为空");
        }
        String sql = "UPDATE a_orders SET `status` = '已取消'  WHERE orderid = ?";
        int update = jdbcTemplate.update(sql, orderid); // 执行sql语句
        if (update == 1) {
            return new ResultUtil<>().setData(null);
        } else {
            return new ResultUtil<>().setErrorMsg("修改失败");
        }
    }


    /**
     * 删除对应订单
     */
    @GetMapping("/delByIds")
    public Result delete(@RequestParam String ids) {
        System.err.println("ids:" + ids);
        String sql = "DELETE FROM a_orders WHERE id IN (" + ids + ")"; // 执行sql语句
        int update = jdbcTemplate.update(sql); // 执行sql语句
        if (update > 0) {
            return new ResultUtil<>().setData(null);
        } else {
            return new ResultUtil<>().setErrorMsg("删除失败");
        }
    }


    //    查询订单数量,根据订单状态
    @GetMapping("/queryCount")
    public Result queryCount(@RequestParam String status) {
        String sql = "SELECT COUNT(*) FROM a_orders WHERE `status` = ?";
        int count = jdbcTemplate.queryForObject(sql, Integer.class, status);
        return new ResultUtil<>().setData(count);
    }

    //    检查订单状态是否为已完成，如果已完成则返回该订单信息，否则返回错误信息
    @GetMapping("/checkOrderStatus")
    public Result checkOrderStatus(@RequestParam String orderId) {
        String sql = "SELECT * FROM a_orders WHERE orderid = ?";
        List<Map<String, Object>> orderList = jdbcTemplate.queryForList(sql, orderId);
        if (orderList.size() > 0) {
            Map<String, Object> order = orderList.get(0);
            if (order.get("status").equals("已完成")) {
                return new ResultUtil<>().setData(order);
            } else {
                return new ResultUtil<>().setSuccessMsg("订单未完成");
            }
        } else {
            return new ResultUtil<>().setErrorMsg("订单不存在");
        }
    }

    /**
     * 提醒接口
     */
    @RequestMapping("/remind/{columnName}/{type}")
    public Result remindCount(@PathVariable("columnName") String columnName, HttpServletRequest request,
                              @PathVariable("type") String type, @RequestParam Map<String, Object> map) {
        return null;
    }


}
